#include "stream_thread.h"
#include "event2/event.h"
#include <unistd.h>
#include <QDebug>

using namespace std;

StreamThread::StreamThread(int id)
    : is_exit_(false), id_(id)
{

}

void StreamThread::AddTask(StreamTask* task)
{
    qInfo("向UDP管程(%d)添加任务", id_);
    task->Build(this->base_);
    task_list_.push_back(task);
}

void StreamThread::RemoveTask(StreamTask *task)
{
    if(IsContain(task))
    {
        qInfo("从UDP管程(%d)删除任务", id_);
        task_list_.remove(task);
    }
}

bool StreamThread::IsContain(StreamTask *task)
{
    for(list<StreamTask*>::iterator it = task_list_.begin(); it != task_list_.end(); it++)
    {
        StreamTask* active_task = *it;
        if(active_task == task)
        {
            return true;
        }
    }
    return false;
}

int StreamThread::TaskSize()
{
    return task_list_.size();
}

void StreamThread::Start()
{
    event_config *conf = event_config_new();
    event_config_set_flag(conf, EVENT_BASE_FLAG_NOLOCK);
    this->base_ = event_base_new_with_config(conf);
    event_config_free(conf);
    if(!this->base_)
    {
        return;
    }

    pthread_create(&th_, NULL, Run, this);
}

void StreamThread::Stop()
{
    is_exit_ = true;
    pthread_join(th_, (void**)NULL);
    // 线程停止通常表示应用关闭
    while(task_list_.size() > 0)
    {
        StreamTask *st = task_list_.front();
        task_list_.pop_front();
        delete st;
    }
    base_ = NULL;
}

void *StreamThread::Run(void *arg)
{  
    StreamThread *self = (StreamThread*)arg;
    qInfo("UDP管程(%d)启动", self->id_);
    while(!self->is_exit_)
    {
        event_base_loop(self->base_, EVLOOP_NONBLOCK);
        usleep(1000);
    }
    event_base_free(self->base_);
}
